package logic

import (
	"baidu/models/cache"
	"baidu/models/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PopularListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPopularListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PopularListLogic {
	return &PopularListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 热门帖子展示
func (l *PopularListLogic) PopularList(in *baidurpc.PopularListRequest) (*baidurpc.PopularListResponse, error) {
	// todo: add your logic here and delete this line

	var popular []mysql.Popular
	mysql.DB.Debug().Find(&popular)

	key := fmt.Sprintf("popular_list_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &popular)
	} else {
		marshal, _ := json.Marshal(popular)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*3)
	}

	var popularList []*baidurpc.PopularList
	for _, m := range popular {
		list := baidurpc.PopularList{
			HeadImage: m.HeadImage,
			Context:   m.Context,
			Collect:   m.Context,
			GiveNum:   int64(m.GiveNum),
		}
		popularList = append(popularList, &list)
	}

	return &baidurpc.PopularListResponse{
		List: popularList,
	}, nil
}
